//
//  CustomCameraController.m
//  DanaKreditLoan
//
//  Created by ZhengChengFeng on 2024/10/29.
//

#import "CustomCameraController.h"

#define kFixHeight  (IS_IPhoneX_All ? kHeight_BottomSafe : 20)

@interface CustomCameraController ()<AVCaptureMetadataOutputObjectsDelegate,AVCapturePhotoCaptureDelegate>


@property (nonatomic) AVCaptureDevice *device;
@property (nonatomic) AVCaptureDeviceInput *input;
@property (nonatomic) AVCaptureMetadataOutput *output;

@property (nonatomic) AVCapturePhotoOutput *ImageOutPut;
@property (nonatomic) AVCapturePhotoSettings *outputSettings;

@property (nonatomic) AVCaptureSession *session;

@property (nonatomic) AVCaptureVideoPreviewLayer *previewLayer;

@property (nonatomic) UIButton *leftButton,*left2Button,*rightButton;
@property (nonatomic) UIView *photoBtnView;

@property (nonatomic) UIImageView *imageView;

@property (nonatomic) UIView *focusView;

@property (nonatomic) UIImage *image;

@property (nonatomic) BOOL canCa;

@end

@implementation CustomCameraController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (BOOL)prefersStatusBarHidden{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self customCamera];
    [self customUI];

}

- (void)customUI{
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kNavigationBarHeight)];
    topView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:topView];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - (100 + kFixHeight), kScreenWidth, 100 + kFixHeight)];
    bottomView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:bottomView];
    
    
    self.photoBtnView =  [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - 80)/2, 20, 80, 80)];
    self.photoBtnView.backgroundColor = [UIColor whiteColor];
    [bottomView addSubview:self.photoBtnView];
    self.photoBtnView.layer.mask = [NSString UIBezierPathWithRect:self.photoBtnView.bounds withCorners:UIRectCornerAllCorners withRadiu:CGSizeMake(40, 40)];
    
    UIView *pvb =  [[UIView alloc] initWithFrame:CGRectMake(5, 5, 70, 70)];
    pvb.backgroundColor = [UIColor blackColor];
    [self.photoBtnView addSubview:pvb];
    pvb.layer.mask = [NSString UIBezierPathWithRect:pvb.bounds withCorners:UIRectCornerAllCorners withRadiu:CGSizeMake(35, 35)];
    
    UIView *pv =  [[UIView alloc] initWithFrame:CGRectMake(7, 7, 66, 66)];
    pv.backgroundColor = [UIColor whiteColor];
    [self.photoBtnView addSubview:pv];
    pv.layer.mask = [NSString UIBezierPathWithRect:pv.bounds withCorners:UIRectCornerAllCorners withRadiu:CGSizeMake(33, 33)];
    
    self.photoBtnView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapClick = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCamera)];
    [self.photoBtnView addGestureRecognizer:tapClick];
    
    self.focusView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    self.focusView.layer.borderWidth = 1.0;
    self.focusView.layer.borderColor =[UIColor greenColor].CGColor;
    self.focusView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.focusView];
    self.focusView.hidden = YES;
    
    self.leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.leftButton.frame = CGRectMake(20, 0, 80, 50);
    [self.leftButton setTitle:ASLocalizedString(@"Cancel") forState:UIControlStateNormal];
    [self.leftButton setTitle:ASLocalizedString(@"Cancel") forState:UIControlStateSelected];
    [self.leftButton setTitle:ASLocalizedString(@"Cancel") forState:UIControlStateHighlighted];
    self.leftButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    self.leftButton.titleLabel.textAlignment = NSTextAlignmentLeft;
    [self.leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:self.leftButton];
    self.leftButton.hidden = NO;
    
    
    self.left2Button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.left2Button.frame = CGRectMake(20, 0, 80, 50);
    [self.left2Button setTitle:ASLocalizedString(@"Retake") forState:UIControlStateNormal];
    [self.left2Button setTitle:ASLocalizedString(@"Retake") forState:UIControlStateSelected];
    [self.left2Button setTitle:ASLocalizedString(@"Retake") forState:UIControlStateHighlighted];
    self.left2Button.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.left2Button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.left2Button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.left2Button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    self.left2Button.titleLabel.textAlignment = NSTextAlignmentLeft;
    [self.left2Button addTarget:self action:@selector(cancle) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:self.left2Button];
    self.left2Button.hidden = YES;
   
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightButton.frame = CGRectMake(kScreenWidth - 20 - 100, 0, 100, 50);
    [self.rightButton setTitle:ASLocalizedString(@"Use Photo") forState:UIControlStateNormal];
    [self.rightButton setTitle:ASLocalizedString(@"Use Photo") forState:UIControlStateSelected];
    [self.rightButton setTitle:ASLocalizedString(@"Use Photo") forState:UIControlStateHighlighted];
    self.rightButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    self.rightButton.titleLabel.textAlignment = NSTextAlignmentRight;
    [self.rightButton addTarget:self action:@selector(changeCamera) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:self.rightButton];
    self.rightButton.hidden = YES;
  
    self.leftButton.centerY = self.photoBtnView.centerY;
    self.left2Button.centerY = self.photoBtnView.centerY;
    self.rightButton.centerY = self.photoBtnView.centerY;
    
    
//    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(focusGesture:)];
//    [self.view addGestureRecognizer:tapGesture];
    
}
- (void)customCamera{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.device = [AVCaptureDevice defaultDeviceWithDeviceType:AVCaptureDeviceTypeBuiltInWideAngleCamera mediaType:AVMediaTypeVideo position:self.isFront ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack];
    
    self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
    
    self.output = [[AVCaptureMetadataOutput alloc]init];
    
    self.ImageOutPut = [[AVCapturePhotoOutput alloc] init];
    
    NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
    AVCapturePhotoSettings *outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
    [self.ImageOutPut setPhotoSettingsForSceneMonitoring:outputSettings];
    self.outputSettings = outputSettings;
    
    self.session = [[AVCaptureSession alloc]init];
    
    if ([self.session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
        self.session.sessionPreset = AVCaptureSessionPreset1280x720;
    }
    
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.ImageOutPut]) {
        [self.session addOutput:self.ImageOutPut];
    }
    
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.previewLayer];
    
    [self.session startRunning];
    if ([_device lockForConfiguration:nil]) {
//        if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
//            [_device setFlashMode:AVCaptureFlashModeAuto];
//        }
//        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
//            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
//        }
        [_device unlockForConfiguration];
    }
}

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position ) return device;
    return nil;
}

- (void)focusGesture:(UITapGestureRecognizer*)gesture{
    CGPoint point = [gesture locationInView:gesture.view];
    [self focusAtPoint:point];
}

- (void)focusAtPoint:(CGPoint)point{
    kWeakSelf
    CGSize size = self.view.bounds.size;
    CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
    NSError *error;
    if ([self.device lockForConfiguration:&error]) {
        
        if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            [self.device setFocusPointOfInterest:focusPoint];
            [self.device setFocusMode:AVCaptureFocusModeAutoFocus];
        }
        
        if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
            [self.device setExposurePointOfInterest:focusPoint];
            [self.device setExposureMode:AVCaptureExposureModeAutoExpose];
        }
        
        [self.device unlockForConfiguration];
        _focusView.center = point;
        _focusView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            weakSelf.focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
        }completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5 animations:^{
                weakSelf.focusView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                weakSelf.focusView.hidden = YES;
            }];
        }];
    }
    
}

- (void)clickCamera{
    
    self.leftButton.hidden = YES;
    self.left2Button.hidden = NO;
    self.rightButton.hidden = NO;
    self.photoBtnView.hidden = YES;
    
    AVCaptureConnection *videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
    
    if (!videoConnection) {
        [self back];
        return;
    }
    
    [self.ImageOutPut capturePhotoWithSettings:self.outputSettings delegate:self];
    

}

- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
    if (!error) {
        NSData *imageData = photo.fileDataRepresentation;
        
        self.image = [UIImage imageWithData:imageData];
        [self.session stopRunning];
        UIGraphicsBeginImageContext(self.image.size);
        [self.image drawInRect:CGRectMake(0, 0, self.image.size.width, self.image.size.height)];
        self.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

    }
}


- (void)cancle{
    [self.imageView removeFromSuperview];
    self.rightButton.hidden = YES;
    self.left2Button.hidden = YES;
    self.leftButton.hidden = NO;
    self.photoBtnView.hidden = NO;
    [self.session startRunning];
}

- (void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)changeCamera{
    [self back];
    NSData *imgData = UIImageJPEGRepresentation(self.image, 0.8);
    if (_callBackPhotoData) {
        _callBackPhotoData(imgData);
    }

}


@end
